﻿using SkiaSharp;

namespace WebMvcDemo
{
    /// <summary>
    /// 创建PDF绘图文件
    /// </summary>
    public class SkiaPdfMaker
    {
        /// <summary>
        /// 每毫米对应多少打印点数 = 每英寸打印多少点数 / 每英寸多少毫米 = 2.83464567
        /// Dpi打印分辨率，Dot Per Inch，每英寸打印点数，默认72
        /// 1英寸=25.4毫米
        /// </summary>
        public const float DotPermm = SKDocument.DefaultRasterDpi / 25.4f;

        /// <summary>
        /// 导出PDF文件
        /// </summary>
        /// <returns></returns>
        public byte[] ExportToPdf()
        {
            Console.WriteLine($"{DateTime.Now}, 开始导出PDF");

            using MemoryStream stream = new MemoryStream();

            var pdfMetadata = new SKDocumentPdfMetadata
            {
                Author = "SkiaPdfMaker",
            };

            //初始化一个PdfDocument类实例
            using SKDocument pdfDocument = SKDocument.CreatePdf(stream, pdfMetadata);

            //新添加一页纸张，创建纸张大小的画布，A4尺寸 = 210 X 297 mm
            float paperWidth = DotPermm * 210;
            float paperHeight = DotPermm * 297;
            var canvas = pdfDocument.BeginPage(paperWidth, paperHeight);

            using var paint = new SKPaint
            {
                Color = SKColors.Black,
                IsAntialias = true,
                Typeface = SkiaChinaFont.ChinaFont,
                TextSize = 24
            };

            string msg = $"{DateTimeOffset.Now:T}, 还有1万行Skia绘图代码...";
            canvas.DrawText(msg, 0, 30, paint);

            using var linePaint = new SKPaint()
            {
                Color = (DateTimeOffset.Now.Second % 4 <= 1) ? SKColors.Red : SKColors.Green,
                Style = SKPaintStyle.Stroke,//不填充
                StrokeWidth = 3,
            };
            canvas.DrawRect(10, 50, paperWidth - 20, paperHeight - 60, linePaint);

            msg += $", linePaint.Color={linePaint.Color}, skContainer.CanvasSize={paperWidth} x {paperHeight}";
            Console.WriteLine(msg);

            //结束一页内容
            pdfDocument.EndPage();

            //结束文档内容
            pdfDocument.Close();

            byte[] ary = stream.ToArray();

            return ary;
        }
    }
}
